package cn.shengchao.examstar.ai.acl.adapters.client;

import cn.shengchao.examstar.ai.acl.ports.IKnowledgePointService;
import cn.shengchao.examstar.knowledge.domain.entity.KnowledgePoint;
import cn.shengchao.examstar.knowledge.shared.service.KnowledgePointSharedService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 知识点服务适配器
 * 实现防腐层端口，屏蔽外部服务实现细节
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class KnowledgePointServiceAdapter implements IKnowledgePointService {

    private final KnowledgePointSharedService knowledgePointSharedService;
    
    @Override
    public List<KnowledgePoint> getKnowledgePointsBySpecificationType(Long specificationTypeId) {
        return knowledgePointSharedService.getKnowledgePointsBySpecificationType(specificationTypeId);
    }
    
    @Override
    public List<KnowledgePoint> getKnowledgeLeafNodesBySpecificationType(Long specificationTypeId) {
        List<KnowledgePoint> allKnowledgePoints = getKnowledgePointsBySpecificationType(specificationTypeId);
        return filterLeafNodes(allKnowledgePoints);
    }
    
    /**
     * 从知识点列表中过滤出叶子节点
     * 
     * @param knowledgePoints 知识点列表
     * @return 叶子节点列表
     */
    private List<KnowledgePoint> filterLeafNodes(List<KnowledgePoint> knowledgePoints) {
        List<KnowledgePoint> leafNodes = new ArrayList<>();
        
        // 创建父节点ID到子节点列表的映射
        Map<Long, List<KnowledgePoint>> parentToChildren = new HashMap<>();
        for (KnowledgePoint point : knowledgePoints) {
            Long parentId = point.getParentId();
            if (!parentToChildren.containsKey(parentId)) {
                parentToChildren.put(parentId, new ArrayList<>());
            }
            parentToChildren.get(parentId).add(point);
        }
        
        // 找出没有子节点的知识点（叶子节点）
        for (KnowledgePoint point : knowledgePoints) {
            if (!parentToChildren.containsKey(point.getId())) {
                leafNodes.add(point);
            }
        }
        
        return leafNodes;
    }
} 